const Service = require('egg').Service;

class CommonService extends Service {

	async getFun (para) {
		const { app } = this;

		const {
			dbname, sql, arr, pageSql, pageSize, pageNo
		} = para;

		console.log(dbname);


		let result = {};

		//分页
		if(pageSql != ''){
			const pageResult = await app.mysql.get(dbname).query(pageSql, arr);
			const totalRecord = pageResult[0].totalRecord;

			const limit = ' limit ' + ((pageNo-1) * pageSize) + ' , ' + pageSize;
			const results = await app.mysql.get(dbname).query(sql + limit, arr);
			const totalPage = totalRecord % pageSize == 0 ?
			parseInt(totalRecord / pageSize) : parseInt(totalRecord / pageSize) + 1

			result = {
				pageNo,
				pageSize,
				totalRecord,
				totalPage,
				results,
			};

		}else{
			result = await app.mysql.get(dbname).query(sql, arr);
		}

		return result;
	}


	//数据库机构存redis
	async sqlToRedis (name) {

  		const { app } = this;

		const result = await app.mysql.get('weshop').query(
			'select id, name, dbname, sqlstr, param ' +
			'from dlq_sql where name = ? ', [name]
		);

		await app.redis.get('system').hset('dlq_sql', name, JSON.stringify(result[0]));

		return JSON.stringify(result[0]);
	}

  	
}

module.exports = CommonService;

